<?php defined('SYSPATH') or die('No direct script access.');

class Model_ParsingTask extends ORM
{ 
    protected $_table_name = 'parsing_tasks';
    protected $_reload_on_wakeup = false;
    
    const CATEGORY_TASK = 1;
    const PRODUCT_TASK  = 2;
    
    public function add_task($url, $type, Model_Shop $shop)
    {
        $url = str_replace('&amp;', '&', $url);
        
        $this->url = $url;
        $this->url_hash = md5($url);
        $this->type = $type;
        $this->shop_id = $shop->id;
        
        try {
            $this->save();   
        } catch (Database_Exception $e) {
            if (strstr($e->getMessage(), 'Duplicate entry') !== false) {
                return null;
            } else {
                die($e->getMessage());
            }
        }
        
        return $this;
    } 
    
    public function add_category_task($url, Model_Shop $shop)
    {
        return $this->add_task($url, Model_ParsingTask::CATEGORY_TASK, $shop);    
    } 
    
    public function add_product_task($url, Model_Shop $shop)
    {
        return $this->add_task($url, Model_ParsingTask::PRODUCT_TASK, $shop);    
    }
    
    public function mark_as_ready()
    {
        $this->is_ready = 1;
        $this->save();
    }
    
    public function get_tasks($type, Model_Shop $shop)
    {
        $tasks = ORM::factory('parsingtask')
                    ->where('type', '=', $type)
                    ->where('shop_id', '=', $shop->id)
                    ->where('is_ready', '=', 0)
                    ->find_all();
                    
        return $tasks;
    }
    
    public function get_category_tasks(Model_Shop $shop)
    {
        return $this->get_tasks(Model_ParsingTask::CATEGORY_TASK, $shop);
    }
    
    public function get_product_tasks(Model_Shop $shop)
    {
        return $this->get_tasks(Model_ParsingTask::PRODUCT_TASK, $shop);
    }   
}